package com.cjm.one.common.utils;


import jakarta.servlet.http.HttpServletRequest;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

public class IpUtils {
    // 私有化构造器防止实例化
    private IpUtils() {}

    // 常见代理头标识（按优先级排序）
    private static final List<String> PROXY_HEADERS = Collections.unmodifiableList(
        Arrays.asList(
            "X-Forwarded-For", 
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_CLIENT_IP",
            "HTTP_X_FORWARDED_FOR"
        )
    );

    // 本地环回地址标识
    private static final String LOCAL_IPV4 = "127.0.0.1";
    private static final String LOCAL_IPV6 = "0:0:0:0:0:0:0:1";
    
    /**
     * 获取客户端真实IP（支持代理穿透）
     * @param request HTTP请求对象
     * @return IP地址或空字符串（未获取到时）
     */
    public static String getClientIp(HttpServletRequest request) {
        if (request == null) return "";

        // 遍历代理头信息
        for (String header : PROXY_HEADERS) {
            String ipList = request.getHeader(header);
            if (isValidIp(ipList)) {
                return parseFirstValidIp(ipList);
            }
        }

        // 直接获取远程地址
        return filterLocalIp(request.getRemoteAddr());
    }

    /**
     * 验证IP有效性
     */
    private static boolean isValidIp(String ip) {
        return ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip);
    }

    /**
     * 解析第一个有效IP
     */
    private static String parseFirstValidIp(String ipList) {
        return Arrays.stream(ipList.split(","))
                .map(String::trim)
                .filter(ip -> !"unknown".equalsIgnoreCase(ip))
                .findFirst()
                .map(IpUtils::filterLocalIp)
                .orElse("");
    }

    /**
     * 过滤本地地址
     */
    private static String filterLocalIp(String ip) {
        if (LOCAL_IPV6.equals(ip)) {
            return LOCAL_IPV4;
        }
        return Optional.ofNullable(ip)
                .filter(s -> !s.isEmpty())
                .orElse("");
    }
}
